import os
from models import *
from utilities import *
from google.appengine.api import users
import UserDict
from Cookie import BaseCookie
from google.appengine.ext import webapp
from django.utils import translation
import hashlib


class LoginControl():

  def Login(self, user, password, externalself, timealive):
    logged = False

    queryuser = CustomUser.all()
    queryuser.filter(' username = ', user)
    passwordencryptor = hashlib.md5()
    passwordencryptor.update(password)
    encpassword = passwordencryptor.hexdigest()
    queryuser.filter(' password = ', encpassword)
    dbusers = queryuser.fetch(1)

    if len(dbusers) > 0:
      logged = True
      dbuser = dbusers[0]
      dbuser.put()
      sessionid = str(dbuser.key())
      cookies = Cookies(externalself, max_age = timealive)
      cookies['sessionid'] = str(dbuser.key())
      if timealive > 300:
        cookies['remember'] = '1'
    else:
      queryuser = CustomUser.all()
      queryuser.filter(' email = ', user)
      passwordencryptor = hashlib.md5()
      passwordencryptor.update(password)
      encpassword = passwordencryptor.hexdigest()
      cookies = Cookies(externalself, max_age = timealive)
      queryuser.filter(' password = ', encpassword)
      dbusers = queryuser.fetch(1)

      if len(dbusers) > 0:
        logged = True
        dbuser = dbusers[0]
        cookies['sessionid'] = str(dbuser.key())
        if timealive > 300:
          cookies['remember'] = '1'
      else:
        logged = False

    if logged:
      return dbuser
    else:
      return 0


  def LoginAuxiliar(self, useremail, tmppassword, externalself, timealive):
    expiredtimedelta = timedelta(hours = 24)
    expireddate = datetime.today() - expiredtimedelta
    querycustomusers = CustomUser.all()
    querycustomusers.filter(' tmppass = ' , tmppassword)
    querycustomusers.filter(' email = ' , useremail)
    querycustomusers.filter(' expire_date > ' , expireddate)
    customusers = querycustomusers.fetch(1)
    if len(customusers) > 0:
      customuser = customusers[0]
      customuser.tmppass = str(random.randint(0,9999999))
      customuser.put()
      sessionid = str(customuser.key())
      cookies = Cookies(externalself, max_age = timealive)
      cookies['sessionid'] = sessionid

      return customuser
    else:
      return 0


  def Logout(self, externalself):
    cookies = Cookies(externalself, max_age = -100)
    if cookies.has_key('sessionid'):
      sessionid = cookies['sessionid']
      del cookies['sessionid']
      cookies['sessionid'] = -1
    if cookies.has_key('remember'):
      del cookies['remember']
      cookies['remember'] = -1
    externalself.redirect("http://wolpyweb.appspot.com/login")
    return 0


  def CheckLogin(self,externalself):
    cookies = Cookies(externalself, max_age = 300)
    dbuser = 0
    if cookies.has_key('remember'):
      if cookies.has_key('sessionid'):
        sessionid = cookies['sessionid']
        dbuser = CustomUser.get(sessionid)
        if dbuser:
          return dbuser
        else:
          sessionid = '-1'
          logged = False
      else:
        sessionid = '-1'
        logged = False
    if not cookies.has_key('sessionid'):
      sessionid = '-1'
      logged = False
    else:
      sessionid = str(cookies['sessionid'])
      logged = False
    if sessionid != '-1':
      if dbuser:
        return dbuser
      else:
        logged = False

    if not logged:
      return 0

  def RegenerateTmppass(self,dbuser):
    dbuser.tmppass = str(random.randint(0,9999999))
    dbuser.put()